//
//  LOLALLHeroViewController.m
//  LOLXXbox
//
//  Created by mac on 16/1/28.
//  Copyright © 2016年 Grasstrio. All rights reserved.
//

#import "LOLALLHeroViewController.h"
#import "LOLBasebutton.h"
#import "LOLBaseCollectionView.h"
#import "LOLAllheroCollectionViewCell.h"
#import "LOLHeroModel.h"
#import "LSZNetWorkTools.h"
#import "LOLChooseCell.h"
#import <UIImageView+WebCache.h>
#import "LOLHerodetaiViewController.h"
#define WIDTH [[UIScreen mainScreen]bounds].size.width
#define HEIGHT [[UIScreen mainScreen]bounds].size.height
#define HEROURL(sn, target)   [[NSString stringWithFormat:@"http://lolbox.duowan.com/phone/apiHeroes.php?serverName=%@&target=%@", sn, target] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

#define HEROHEADURL(name) [NSString stringWithFormat:@"http://img.lolbox.duowan.com/champions/%@_120x120.jpg",name]

#define PADDING5 WIDTH/75

#define PADDING10 WIDTH/37.5b
#define TOPCHOOSEHEIGHT 30
@interface LOLALLHeroViewController ()<UISearchBarDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,retain)UIView *allHeroView;
@property(nonatomic,retain)LOLBaseCollectionView *allCollectionView;
@property(nonatomic,retain)NSMutableArray *displayArr;
@property(nonatomic,retain)NSArray *locationArr;
@property(nonatomic,retain)LOLBaseCollectionView *choose1;
@property(nonatomic,retain)LOLBaseCollectionView *choose2;
@property(nonatomic,retain)LOLBaseCollectionView *choose3;
@property(nonatomic,retain)LOLBaseCollectionView *choose4;
@property(nonatomic,retain)NSOperationQueue *queue;
@property(nonatomic,retain)UIImageView *imageView2;
@property(nonatomic,retain)UIImageView *imageView3;
@property(nonatomic,retain)UIImageView *imageView4;
@property(nonatomic,retain)NSArray *typeDisplayArr;
@property(nonatomic,copy)NSString *panduan;
@property(nonatomic,retain)NSMutableArray *allHeroArr;
@property(nonatomic,retain)NSArray *sortArr;
@property(nonatomic,retain)NSMutableArray *tempSortArr;
@property(nonatomic,retain)NSMutableArray *attackSortArr;
@property(nonatomic,retain)NSMutableArray *magicSortArr;
@property(nonatomic,retain)NSMutableArray *defenseSortArr;
@property(nonatomic,retain)NSMutableArray *operationSortArr;
@property(nonatomic,retain)NSMutableArray *nopaySortArr;
@property(nonatomic,retain)NSMutableArray *paySortArr;
@property(nonatomic,retain)NSMutableArray *wordSortArr;

@property(nonatomic,retain)NSArray *twoLevelPayArr;
@property(nonatomic,retain)NSArray *twoLevelNoPayArr;

@property(nonatomic,retain)LOLBaseCollectionView *choose1collectionView;
@property(nonatomic,retain)LOLBaseCollectionView *choose2collectionView;
@property(nonatomic,retain)UITableView *oneLevelTableView;
@property(nonatomic,retain)LOLBaseCollectionView *chooseCollectionView;

@end

@implementation LOLALLHeroViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.navigationItem.title=@"英雄";
    self.locationArr=@[@"全部",@"上单",@"中单",@"ADC",@"打野"];
    self.sortArr=@[@"默认",@"物攻",@"法伤",@"防御",@"操作",@"金币",@"点券",@"字母"];
    self.twoLevelNoPayArr=@[@"450",@"1350",@"3150",@"4800",@"6300"];
    self.twoLevelPayArr=@[@"1000",@"1500",@"2000",@"2500",@"3000",@"3500",@"4000",@"4500"];
    self.allHeroView.hidden = YES;
    [self getData];
    [self createAllHeroView];
    [self createChooseCategoryView];
    
}


- (void)getData {
    [LSZNetWorkTools getWithUrl:HEROURL(@"nil" ,@"nil") parameter:nil httpHeader:nil resposeType:ResponseTypeJSON success:^(id result) {
       
        self.allHeroArr = [LOLHeroModel baseModelByArr:result[@"all"]];
        self.displayArr=self.allHeroArr;
        self.tempSortArr=[NSMutableArray arrayWithArray:self.allHeroArr];
        [self sortOperation];
        [self.allCollectionView reloadData];
        
        NSString *sanboxPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask , YES)[0];
        NSString *documentPath=[sanboxPath stringByAppendingPathComponent:@"allHero.test"];
        [NSKeyedArchiver archiveRootObject:self.allHeroArr toFile:documentPath];
        


    } fail:^(NSError *error) {
        
        
    }];
}

-(void)sortOperation{
    NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
        self.attackSortArr=[NSMutableArray arrayWithArray:[self bubbleProperty_sort:self.tempSortArr sortRule:0]];
        [NSThread currentThread];
    }];
    
    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        self.magicSortArr=[NSMutableArray arrayWithArray:[self bubbleProperty_sort:self.tempSortArr sortRule:2]];
        
    }];
    
    NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
        self.defenseSortArr=[NSMutableArray arrayWithArray:[self bubbleProperty_sort:self.tempSortArr sortRule:1]];
        
    }];
    
    NSBlockOperation *operation4 = [NSBlockOperation blockOperationWithBlock:^{
        self.operationSortArr=[NSMutableArray arrayWithArray:[self bubbleProperty_sort:self.tempSortArr sortRule:3]];
        
    }];
    
    NSBlockOperation *operation5 = [NSBlockOperation blockOperationWithBlock:^{
        self.nopaySortArr=[NSMutableArray arrayWithArray:[self bubblePrice_sort:self.tempSortArr sortRule:0]];
        
    }];
    
    NSBlockOperation *operation6 = [NSBlockOperation blockOperationWithBlock:^{
        self.paySortArr=[NSMutableArray arrayWithArray:[self bubblePrice_sort:self.tempSortArr sortRule:1]];
        
    }];
    
    NSBlockOperation *operation7 = [NSBlockOperation blockOperationWithBlock:^{
        self.wordSortArr=[NSMutableArray arrayWithArray:[self bubbleWord_sort:self.tempSortArr]];
        
    }];
    
    
    
    
    
    
    self.queue=[[NSOperationQueue alloc]init];
    self.queue.maxConcurrentOperationCount = 3;
    [self.queue addOperations:@[operation1,operation2,operation3,operation4,operation5,operation6,operation7] waitUntilFinished:NO];
    
    
    
}


-(void)createAllHeroView{
    self.allHeroView = [[UIView alloc]initWithFrame:CGRectMake(0, TOPCHOOSEHEIGHT, WIDTH, HEIGHT-64-49)];
    [self.view addSubview:self.allHeroView];

    
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, WIDTH, WIDTH/12.5)];
    searchBar.placeholder = @"请输入英雄关键字   ";
    searchBar.delegate = self;
    [self.view addSubview:searchBar];

    
    NSArray *arr = @[@"价格 ﹀" ,@"位置 ﹀" ,@"排序 ﹀" ];
    for (int i  =  0; i<3;i++) {
        LOLBasebutton *button = [LOLBasebutton baseButtonFrame:CGRectMake(WIDTH/3*i, 5, WIDTH/3, WIDTH/18.75) buttonType:UIButtonTypeSystem buttonTitle:arr[i] buttonTitleColor:[UIColor blackColor] buttonTag:201+i buttonImage:nil];
        button.titleLabel.font=[UIFont systemFontOfSize:15];
        [button addTarget:self action:@selector(chooseCategoryButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.allHeroView addSubview:button];
        
    }
    self.allCollectionView = [[LOLBaseCollectionView alloc]initWithFrame:CGRectMake(0, 10 + WIDTH/18.75, WIDTH,self.allHeroView.frame.size.height-WIDTH/12.5-TOPCHOOSEHEIGHT-WIDTH/37.5) flowLayoutItemSize:CGSizeMake(WIDTH/4-10, HEIGHT/6) xSpace:1 ySpace:1 sectionInSet:UIEdgeInsetsMake(0, WIDTH/53.5, WIDTH/53.5, WIDTH/53.5) cell:[LOLAllheroCollectionViewCell class] reuse:@"allHeroReuse"];
    self.allCollectionView.delegate = self;
    self.allCollectionView.dataSource = self;
    [self.allHeroView addSubview:self.allCollectionView];

    
}
-(void)createChooseCategoryView{
    
    self.choose1collectionView = [[LOLBaseCollectionView  alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 60) flowLayoutItemSize:CGSizeMake((WIDTH-25)/4, 20) xSpace:5 ySpace:5 sectionInSet:UIEdgeInsetsMake(5, 5, 5, 5) cell:[LOLChooseCell class] reuse:@"choose1CateReuse"];
    self.choose1collectionView.delegate=self;
    self.choose1collectionView.dataSource=self;
    self.choose1collectionView.hidden=YES;
    [self.allHeroView addSubview:self.choose1collectionView];

    
    self.choose2collectionView=[[LOLBaseCollectionView  alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 60) flowLayoutItemSize:CGSizeMake((WIDTH-25)/4, 20) xSpace:5 ySpace:5 sectionInSet:UIEdgeInsetsMake(5, 5, 5, 5) cell:[LOLChooseCell class] reuse:@"choose2CateReuse"];
    
        self.choose2collectionView.delegate=self;
        self.choose2collectionView.dataSource=self;
        self.choose2collectionView.hidden=YES;
        [self.allHeroView addSubview:self.choose2collectionView];
    
    self.oneLevelTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 90) style:UITableViewStylePlain];
    
    self.oneLevelTableView.delegate=self;
    self.oneLevelTableView.dataSource=self;
    self.oneLevelTableView.hidden=YES;
    self.oneLevelTableView.rowHeight =30;
    self.oneLevelTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.allHeroView addSubview:self.oneLevelTableView];
    
    

        self.chooseCollectionView=[[LOLBaseCollectionView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, 60) flowLayoutItemSize:CGSizeMake((WIDTH-25)/4, 20) xSpace:5 ySpace:5 sectionInSet:UIEdgeInsetsMake(5, 5, 5, 5) cell:[LOLChooseCell class] reuse:@"chooseCateReuse"];
    
        self.chooseCollectionView.delegate=self;
        self.chooseCollectionView.dataSource=self;
        self.chooseCollectionView.hidden=YES;
        [self.allHeroView addSubview:self.chooseCollectionView];
    
}

-(NSMutableArray *)bubblePrice_sort:(NSMutableArray *)arr sortRule:(NSInteger)num{
    
    NSMutableArray *sortArr=[NSMutableArray arrayWithArray:arr];
    
    
    
    
    for (int i = 0; i<sortArr.count-1; i++) {
        
        for (int j = 0; j<sortArr.count-i-1; j++) {
            
            
            if (((NSString *)[((LOLHeroModel *)sortArr[j]).price componentsSeparatedByString:@","][num]).integerValue<((NSString *)[((LOLHeroModel *)sortArr[j+1]).price componentsSeparatedByString:@","][num]).integerValue) {
                LOLHeroModel *temp=sortArr[j];
                sortArr[j]=sortArr[j+1];
                sortArr[j+1]=temp;
            }
        }
        
        
        
    }
    
    
    return sortArr;
    
}

-(NSMutableArray *)bubbleWord_sort:(NSMutableArray *)arr{
    
    NSMutableArray *sortArr=[NSMutableArray arrayWithArray:arr];
    for (int i = 0; i<sortArr.count-1; i++) {
        
        for (int j = 0; j<sortArr.count-i-1; j++) {
            
            if ([(NSString *)((LOLHeroModel *)sortArr[j]).enName compare: (NSString *)((LOLHeroModel *)sortArr[j+1]).enName]>0) {
                
                LOLHeroModel *temp=sortArr[j];
                sortArr[j]=sortArr[j+1];
                sortArr[j+1]=temp;
            }
        }
        
        
        
    }
    
    return sortArr;
    
}

-(NSMutableArray *)bubbleProperty_sort:(NSMutableArray *)arr sortRule:(NSInteger)num{
    
    
    NSMutableArray *sortArr=[NSMutableArray arrayWithArray:arr];
    
    for (int i = 0; i<sortArr.count-1; i++) {
        
        for (int j = 0; j<sortArr.count-i-1; j++) {
            
            
            if (((NSString *)[((LOLHeroModel *)sortArr[j]).rating componentsSeparatedByString:@","][num]).integerValue<((NSString *)[((LOLHeroModel *)sortArr[j+1]).rating componentsSeparatedByString:@","][num]).integerValue) {
                LOLHeroModel *temp=sortArr[j];
                sortArr[j]=sortArr[j+1];
                sortArr[j+1]=temp;
            }
        }
        
        
        
    }
    
    
    return sortArr;
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
  if (collectionView == self.chooseCollectionView)
    {
        
        return self.typeDisplayArr.count;
        
    }
    else if(collectionView == self.choose1collectionView)
    {
        return self.locationArr.count;
        
    }
    else if(collectionView == self.choose2collectionView)
    {
        return self.sortArr.count;
    }
    else
    {
        
        return self.displayArr.count;
        
    }
    
    
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
     if(collectionView == self.chooseCollectionView){
        
        LOLChooseCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"chooseCateReuse" forIndexPath:indexPath];
        cell.typeLabel.text=self.typeDisplayArr[indexPath.item];
        return cell;
        
    }
    else if(collectionView == self.choose1collectionView){
        
        LOLChooseCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"choose1CateReuse" forIndexPath:indexPath];
        cell.typeLabel.text=self.locationArr[indexPath.item];
        return cell;
        
        
    }
    else if(collectionView == self.choose2collectionView){
        
        LOLChooseCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"choose2CateReuse" forIndexPath:indexPath];
        cell.typeLabel.text=self.sortArr[indexPath.item];
        return cell;
        
        
    }
    
    else{
        LOLAllheroCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"allHeroReuse" forIndexPath:indexPath];
        
        
        LOLHeroModel *heroModel = self.displayArr[indexPath.item];
        
        [cell.heroImageView sd_setImageWithURL:[NSURL URLWithString:HEROHEADURL(heroModel.enName)] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        cell.cnName.text = heroModel.title;
        
        return cell;
    }
    
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (collectionView == self.choose1collectionView) {
        
        NSMutableArray *searchArr=[NSMutableArray arrayWithArray:self.allHeroArr];
        if (indexPath.row != 0) {
            NSPredicate *predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"Location CONTAINS[cd] '%@'",self.locationArr[indexPath.row]]];
            [searchArr filterUsingPredicate:predicate];
        }
        self.displayArr = searchArr;
        [self.allCollectionView reloadData];
        [((UIButton *)[self.allHeroView viewWithTag:202]) setTitle:[NSString stringWithFormat:@"%@ ﹀",self.locationArr[indexPath.row]] forState:UIControlStateNormal];
        self.choose1collectionView.hidden=YES;
        
        
    }
    else if(collectionView == self.choose2collectionView){
        
        switch (indexPath.row) {
            case 0:
                if (self.displayArr!=self.allHeroArr) {
                    self.displayArr=self.allHeroArr;
                    [self.allCollectionView reloadData];
                    
                }
                break;
            case 1:
                if (self.displayArr!=self.attackSortArr) {
                    
                    self.displayArr=self.attackSortArr;
                    [self.allCollectionView reloadData];
                }
                
                break;
                
            case 2:
                if (self.displayArr!=self.magicSortArr) {
                    
                    self.displayArr=self.magicSortArr;
                    [self.allCollectionView reloadData];
                }
                
                break;
                
            case 3:
                if (self.displayArr!=self.defenseSortArr) {
                    
                    self.displayArr=self.defenseSortArr;
                    [self.allCollectionView reloadData];
                }
                
                break;
                
            case 4:
                if (self.displayArr!=self.operationSortArr) {
                    
                    self.displayArr=self.operationSortArr;
                    [self.allCollectionView reloadData];
                }
            case 5:
                if (self.displayArr!=self.nopaySortArr) {
                    
                    self.displayArr=self.nopaySortArr;
                    [self.allCollectionView reloadData];
                }
            case 6:
                if (self.displayArr!=self.paySortArr) {
                    
                    self.displayArr=self.paySortArr;
                    [self.allCollectionView reloadData];
                }
            case 7:
                if (self.displayArr!=self.wordSortArr) {
                    
                    self.displayArr=self.wordSortArr;
                    [self.allCollectionView reloadData];
                }
                
                break;
                
                
            default:
                break;
        }
        
        [((UIButton *)[self.allHeroView viewWithTag:203]) setTitle:[NSString stringWithFormat:@"%@ ﹀",self.sortArr[indexPath.row]] forState:UIControlStateNormal];
        self.choose2collectionView.hidden=YES;
        
        
    }
    else if(collectionView == self.chooseCollectionView){
        
        NSMutableArray *searchArr=[NSMutableArray arrayWithArray:self.allHeroArr];
        NSPredicate *predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"price CONTAINS[cd] '%@'",self.typeDisplayArr[indexPath.row]]];
        [searchArr filterUsingPredicate:predicate];
        
        self.displayArr = searchArr;
        [self.allCollectionView reloadData];
        
        [((UIButton *)[self.allHeroView viewWithTag:201]) setTitle:[NSString stringWithFormat:@"%@ ﹀",self.typeDisplayArr[indexPath.row]] forState:UIControlStateNormal];
        
        self.chooseCollectionView.hidden = YES;
    }
    
    else{
        
//        NSArray *arr = (collectionView == self.freeCollectionView?self.freeHeroArr:self.displayArr);
        LOLHeroModel *model = self.displayArr[indexPath.row];
//
//        
        LOLHerodetaiViewController *heroDetailVC = [[LOLHerodetaiViewController alloc]init];
        heroDetailVC.heroModel = model;
        [self.navigationController pushViewController:heroDetailVC animated:YES];
     
    }
    
}

-(void)chooseCategoryButton:(UIButton *)button{
    switch (button.tag) {
        case 201:
            self.oneLevelTableView.hidden = !self.oneLevelTableView.hidden;
            self.choose1collectionView.hidden =YES;
            self.choose2collectionView.hidden =YES;
            self.chooseCollectionView.hidden = YES;
            break;
        case 202:
            self.choose1collectionView.hidden = !self.choose1collectionView.hidden;
            self.oneLevelTableView.hidden = YES;
            self.choose2collectionView.hidden=YES;
            self.chooseCollectionView.hidden=YES;
            break;
        case 203:
            self.choose2collectionView.hidden = !self.choose2collectionView.hidden;
            self.oneLevelTableView.hidden = YES;
            self.choose1collectionView.hidden = YES;
            self.chooseCollectionView.hidden=YES;
            break;
        default:
            break;
    }
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView==self.oneLevelTableView ) {
        return 3;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    
    if (tableView == self.oneLevelTableView ) {
        
        static NSString *reuse=@"levelReuse";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
            cell.textLabel.font=[UIFont systemFontOfSize:15];
            cell.backgroundColor = [UIColor grayColor];
        }
        
        cell.textLabel.text=@[@"金币",@"点券",@"全部"][indexPath.row];
        
        
        
        
        return cell;
        
    }
    return nil;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView==self.oneLevelTableView) {
        
        switch (indexPath.row) {
            case 0:
                self.typeDisplayArr=self.twoLevelNoPayArr;
                self.chooseCollectionView.hidden=NO;
                [self.chooseCollectionView reloadData];
                break;
            case 1:
                self.typeDisplayArr=self.twoLevelPayArr;
                self.chooseCollectionView.hidden=NO;
                [self.chooseCollectionView reloadData];
                break;
                
            case 2:
                [((UIButton *)[self.allHeroView viewWithTag:201]) setTitle:@"全部 ﹀" forState:UIControlStateNormal];
                if (self.displayArr != self.allHeroArr) {
                    self.displayArr=self.allHeroArr;
                    [self.allCollectionView reloadData];
                    
                }
                
                
                break;
                
                
            default:
                break;
        }
        
        self.oneLevelTableView.hidden=YES;
    }
    
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([searchText isEqualToString:@""]) {
        self.displayArr = self.allHeroArr;
        [self.allCollectionView reloadData];
    }
    
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSMutableArray *searchArr=[NSMutableArray arrayWithArray:self.allHeroArr];
    
    NSPredicate *predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"enName CONTAINS[cd] '%@' OR cnName  CONTAINS[cd] '%@' OR  title CONTAINS[cd] '%@'",searchBar.text,searchBar.text,searchBar.text]];
    
    
    [searchArr filterUsingPredicate:predicate];
    
    
    self.displayArr = searchArr;
    [self.allCollectionView reloadData];
    
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
